<script setup lang="ts">
const loading = ref(false)
const dataSource = ref<Api.BookItem>({})
const formRef = ref()

onLoad(async (option) => {
  if (option?.id) {
    uni.setNavigationBarTitle({
      title: '编辑',
    })
    dataSource.value = await apiBookItemGet({ id: option.id })
  }
  else {
    dataSource.value.bookId = option?.bookId
  }
})

const onSubmit = async () => {
  const { valid } = await formRef.value.validate()
  if (!valid)
    return
  loading.value = true
  const api = dataSource.value.id ? apiBookItemPut : apiBookItemPost
  await api(dataSource.value)
  uni.navigateBack()
  uni.showToast({
    title: '保存成功',
    icon: 'none',
  })

  loading.value = false
}

const onSelectFriend = () => {
  uni.navigateTo({
    url: '/pages/friend/select',
    events: {
      acceptDataFromOpenedPage(e: Api.Friend) {
        dataSource.value.friendId = e.id
        dataSource.value.friendName = e.name
      },
    },
  })
}
const presetMoney = [200, 500, 1000, 2000]
</script>

<template>
  <div class="mx-3 space-y-3">
    <div class="rounded-2xl bg-white p-2 py-5">
      <wd-form ref="formRef" :model="dataSource">
        <wd-input v-if="!dataSource.id" v-model="dataSource.friendName" label="亲友" prop="friendName" placeholder="点击右侧图标选择亲友"
                  :rules="[{ required: true, message: '请输入亲友姓名' }]"
        >
          <template #suffix>
            <div class="i-hugeicons-contact-01 text-base text-gray" @click="onSelectFriend" />
          </template>
        </wd-input>
        <wd-input v-model="dataSource.money" label="礼金" prop="money" placeholder="随礼金额" type="number"
                  :rules="[{ required: true, message: '请填写随礼金额' }]"
        />
        <div class="flex justify-end space-x-2">
          <div v-for="i in presetMoney" :key="i">
            <wd-button plain size="small" @click="dataSource.money = i">
              {{ i }}
            </wd-button>
          </div>
        </div>
        <wd-input v-model="dataSource.attendance" label="出席" prop="attendance" type="number" placeholder="参加宴席人数" />
        <wd-input v-model="dataSource.remarks" label="备注" placeholder="请输入内容" />
      </wd-form>
    </div>

    <wd-button block :loading="loading" @click="onSubmit">
      保存
    </wd-button>
  </div>
</template>

<style lang="scss" scoped></style>

<route lang="json">
{
  "style": {
    "navigationBarTitleText": "收礼记录"
  }
}
</route>
